package com.gq.utils;

import org.json.JSONException;
import org.json.JSONObject;

import iu.gq.db.items.ChapterItem;
import iu.gq.template.GQApplication;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class SharePreferenceUtil {
	
	private Context context;
	private static SharePreferenceUtil instance;
	private SharedPreferences sharePreference;
	
	public SharePreferenceUtil(Context context) {
		this.context = context;
		sharePreference = context.getSharedPreferences(GQApplication.getContext().getPackageName(), Context.MODE_PRIVATE);
	}
	
	public int getDbVersion() {
		int dbVersion = sharePreference.getInt("DBVERSION", 1);
		return dbVersion;
	}
	
	public void setDbVersion(int version) {
		Editor editor = sharePreference.edit();
		editor.putInt("DBVERSION", version);
		editor.commit();
	}
	
	public void setLastChapter(ChapterItem chapter) {
		Editor editor = sharePreference.edit();
		editor.putString("lastchapter", chapter.toJson());
		editor.commit();
		setNotification();
	}
	
	public void setNotification() {
		Editor editor = sharePreference.edit();
		editor.putBoolean("notification", true);
		editor.commit();
	}
	
	public void removeNotification() {
		Editor editor = sharePreference.edit();
		editor.putBoolean("notification", false);
		editor.commit();
	}
	
	public boolean isShowNotification() {
		boolean isShow = sharePreference.getBoolean("notification", false);
		return isShow;
	}
	
	public ChapterItem getLastChapter() {
		String jsonStr = sharePreference.getString("lastchapter", null);
		if (jsonStr == null) return null;
		ChapterItem item = null;
		try {
			item = new ChapterItem(new JSONObject(jsonStr));
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return item;
	}
	
	public static SharePreferenceUtil getInstance(Context context) {
		if (instance == null) {
			instance = new SharePreferenceUtil(context);
		}
		return instance;
	}
}
